package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.IntoPiecesInfo;
import com.eeepay.eeepay_v2.model.LimitInfo;
import com.eeepay.eeepay_v2.model.PaperFile;
import com.eeepay.eeepay_v2.model.RateInfo;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.BtnStyleUtil;
import com.eeepay.eeepay_v2.util.ConfigPorperties;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.DataUtils;
import com.eeepay.eeepay_v2.util.FileUtil;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.SPUtils;
import com.eeepay.eeepay_v2.util.StatuUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.util.ScreenSwitch;
import com.eeepay.v2_library.view.HorizontalItemView;
import com.eeepay.v2_library.view.LabelEditText;
import com.eeepay.v2_library.view.TitleBar;

import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.MerAddModular;
import cn.eeepay.api.grpc.nano.MerAddServiceGrpc;
import io.grpc.ManagedChannel;

/**
 * Created by Ching on 2016/3/8.
 * 资料完善
 */
public class CompleteDataActivity extends ABBaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, TitleBar.LeftBtnOnClickListener {

    private HorizontalItemView dataHiv, basicHiv, bisInfoHiv, settlemenHiv, rateHiv, limitHiv;//证件资料
    private LabelEditText phoneLet, snoLet, remarksLet;//商户手机号，机具SN号
    private TitleBar titleBar;
    private Button submitBtn;//提交
    private TextView agreeTv;
    private CheckBox agreeCb;//是否同意服务协议
    private boolean isClick = false;
    private boolean isChecked = false;
    private IntoPiecesInfo intoPieces;

    private List<RateInfo> rateList;
    private List<LimitInfo> limitList;
    private List<PaperFile> fileList;

    private DataEditListener editListener;
    private final int CHECK = 0;
    private final int SERVICE = 1;
    private final int COMMIT = 2;
    private final int DEVICE = 3;

    private String phone;
    private String remark;
    private String sno;

    private MerAddModular.ServiceInfo[] serviceInfos;
    private UserInfo userInfo;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_complete_info;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.tb_complete_info);

        dataHiv = getViewById(R.id.hiv_data);
        basicHiv = getViewById(R.id.hiv_basic);
        bisInfoHiv = getViewById(R.id.hiv_bis_info);
        settlemenHiv = getViewById(R.id.hiv_settlemen);
        rateHiv = getViewById(R.id.hiv_service_rate);
        limitHiv = getViewById(R.id.hiv_service_limit);

        phoneLet = getViewById(R.id.let_merchant_phone);
        snoLet = getViewById(R.id.let_sno);
        phoneLet.getEditText().setEnabled(false);
        snoLet.getEditText().setEnabled(false);
//        phoneLet.getEditText().setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
        remarksLet = getViewById(R.id.let_remarks);
        submitBtn = getViewById(R.id.btn_data_submit);
        agreeTv = getViewById(R.id.tv_agreement);
        agreeCb = getViewById(R.id.cb_agreement);

    }

    @Override
    protected void eventOnClick() {


        intoPieces = SPUtils.getIntoPieces();

        userInfo = UserInfo.getInstance();
        if (intoPieces != null) {
            phoneLet.setEditContent(intoPieces.getMerPhone());
            snoLet.setEditContent(intoPieces.getSno());
            Log.d("proInfo", "CompleteData : Industry->" + intoPieces.getIndustry()
                    + "   BisType" + intoPieces.getBisType());
            Log.d("proInfo", " id " + intoPieces.getProId());
        }
//        sendHttpRequest(DEVICE);
        titleBar.setLeftOnClickListener(this);

        dataHiv.setOnClickListener(this);
        basicHiv.setOnClickListener(this);
        bisInfoHiv.setOnClickListener(this);
        settlemenHiv.setOnClickListener(this);
        rateHiv.setOnClickListener(this);
        limitHiv.setOnClickListener(this);

//        dataHiv.setRightText("已完成");
//        basicHiv.setRightText("已完成");
//        bisInfoHiv.setRightText("已完成");
//        settlemenHiv.setRightText("已完成");
//        rateHiv.setRightText("已完成");
//        limitHiv.setRightText("已完成");

        agreeTv.setOnClickListener(this);
        submitBtn.setOnClickListener(this);
        agreeCb.setOnCheckedChangeListener(this);
        agreeCb.setChecked(true);

        editListener = new DataEditListener();
        phoneLet.getEditText().addTextChangedListener(editListener);
        snoLet.getEditText().addTextChangedListener(editListener);
        remarksLet.getEditText().addTextChangedListener(editListener);

        fileList = SPUtils.getList(Constant.KEY.PAPER_FILE);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.hiv_data://证件资料
//                List<PaperFile> datas = SPUtils.getList(Constant.KEY.PAPER_FILE);
                if (fileList == null || fileList.size() == 0) {//证件照要求项为空时不进入证件资料界面
                    dataHiv.setRightText("已完成");
                    return;
                }
                ScreenSwitch.switchActivity(this, PapersActivity.class, null, Constant.RequestCode.PAPERS);
                break;
            case R.id.hiv_basic://基本信息
                intoPieces.setSno(snoLet.getEditContent());
                ScreenSwitch.switchActivity(this, BasicDataActivity.class, null, Constant.RequestCode.BASIC_DATA);
                break;
            case R.id.hiv_bis_info://经营信息
                ScreenSwitch.switchActivity(this, BisInfoActivity.class, null, Constant.RequestCode.BIS_INFO);
                break;
            case R.id.hiv_settlemen://结算信息
                ScreenSwitch.switchActivity(this, SettlementActivity.class, null, Constant.RequestCode.SETTLEMENT);
                break;
            case R.id.hiv_service_rate://服务费率
                ScreenSwitch.switchActivity(this, ServiceRateActivity.class, null, Constant.RequestCode.SERVICE_RATE);
                break;
            case R.id.hiv_service_limit://服务限额
                ScreenSwitch.switchActivity(this, ServiceLimitActivity.class, null, Constant.RequestCode.SERVICE_LIMIT);
                break;
            case R.id.tv_agreement:
                Bundle bundle = new Bundle();
                bundle.putString(Constant.INTENT_FLAG, Constant.AGREEMENT);
                goActivity(WebViewActivity.class, bundle);
                break;
            case R.id.btn_data_submit://提交
                phone = phoneLet.getEditContent();
                remark = remarksLet.getEditContent();
                sno = snoLet.getEditContent();
                sendHttpRequest(COMMIT);
                break;
        }
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , taskId, new GrpcUtils.AsyncTaskListener() {
                    @Override
                    public Object doInBack(ManagedChannel channel, int taskId) {
                        MerAddModular.MyResponse response = null;
                        MerAddServiceGrpc.MerAddServiceBlockingStub stub = null;

                        switch (taskId) {
//                            case DEVICE:
//                                stub = MerAddServiceGrpc
//                                        .newBlockingStub(channel);
//                                MerAddModular.RegistRulesReq regRequest = new MerAddModular.RegistRulesReq();
//                                regRequest.agentNo = userInfo.getAgentNo();
//                                regRequest.sn = intoPieces.getSno();
//                                regRequest.mobilephone = intoPieces.getMerPhone();
//                                regRequest.teamId = ConfigPorperties.getInstance().getTeamId();
//                                regRequest.bpId = intoPieces.getProId();
//                                return stub.checkRegistRules(regRequest);
//                            case SERVICE://选择的业务产品
//                                stub = MerAddServiceGrpc
//                                        .newBlockingStub(channel)
//                                        .withDeadlineAfter(5, TimeUnit.SECONDS);
//                                MerAddModular.GetServiceReq request = new MerAddModular.GetServiceReq();
////                                request.agentNo = "10000";
////                                request.oneAgentNo = "0";
//                                request.bpId = intoPieces.getProId();
//                                request.agentNo = userInfo.getAgentNo();
//                                request.oneAgentNo = userInfo.getOneAgentNo();
//
//                                return stub.getServiceInfoByParams(request);
//                                break;
                            case COMMIT://最后提交
                                stub = MerAddServiceGrpc
                                        .newBlockingStub(channel)
                                        .withDeadlineAfter(45, TimeUnit.SECONDS);
                                return commitData(stub);
                        }
                        return null;
                    }

                    @Override
                    public void updateUI(Object result, int taskId) {
                        dismissProgressDialog();
                        MerAddModular.MyResponse response = (MerAddModular.MyResponse) result;
//                        if (result == null) {
//                            showToast("获取数据失败,请重试");
//                            finish();
//                            return;
//                        }

//                        if (!TextUtils.isEmpty(response.resMsg.msg)) {
//                            showToast(response.resMsg.msg.toString());
//                            Log.d("response", " response: " + response.resMsg.msg.toString());
//                        }
                        switch (taskId) {
//                            case DEVICE:
//                                if (result == null) {
//                                    showToast("机具校验失败，请重试");
//                                    finish();
//                                    return;
//                                }
//                                if (response.resMsg.status) {
//                                    sendHttpRequest(SERVICE);
//                                } else {
//                                    showToast(response.resMsg.msg.toString());
//                                    finish();
//                                }
//                                break;
//                            case CHECK:
//                                if (result == null) {
//                                    showToast("注册验证失败，请重试");
//                                    return;
//                                }
//                                if (!TextUtils.isEmpty(response.resMsg.msg)) {
//                                    showToast(response.resMsg.msg.toString());
//                                    Log.d("response", " response: " + response.resMsg.msg.toString());
//                                }
//                                break;
//                            case SERVICE:
//                                if (result == null) {
//                                    showToast("获取进件项失败，请重试");
//                                    finish();
//                                    return;
//                                } else if ("当前业务产品无服务".equals(response.resMsg.msg)) {
//                                    finish();
//                                } else {
//                                    getService(response);
//                                }
//                                break;
                            case COMMIT:
                                if (result == null) {
                                    showToast("进件提交失败");
                                    return;
                                } else {
                                    showToast(response.resMsg.msg);
                                    Log.d("response", " response1: " + response.resMsg.msg.toString());
                                }
                                if (response.resMsg.status) {
                                    showToast(response.resMsg.msg);
                                    Log.d("response", " response2: " + response.resMsg.msg.toString());
                                    //清楚本地存储的数据
                                    SPUtils.removeList(SPUtils.getList(Constant.KEY.RATE).size(), Constant.KEY.RATE);
                                    SPUtils.removeList(SPUtils.getList(Constant.KEY.LIMIT).size(), Constant.KEY.LIMIT);
                                    SPUtils.removeList(SPUtils.getList(Constant.KEY.PAPER_FILE).size(), Constant.KEY.PAPER_FILE);
                                    StatuUtils.removeStatu();
                                    SPUtils.removeHistory("IntoPiecesInfo");
                                    finish();
                                }
                                break;
                        }
                    }
                });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        String status = data.getStringExtra("status");
        switch (requestCode) {
            case Constant.RequestCode.PAPERS:
                dataHiv.setRightText(status);
                break;
            case Constant.RequestCode.BASIC_DATA:
                basicHiv.setRightText(status);
                break;
            case Constant.RequestCode.BIS_INFO:
                bisInfoHiv.setRightText(status);
                break;
            case Constant.RequestCode.SETTLEMENT:
                settlemenHiv.setRightText(status);
                break;
            case Constant.RequestCode.SERVICE_RATE:
                rateHiv.setRightText(status);
                break;
            case Constant.RequestCode.SERVICE_LIMIT:
                limitHiv.setRightText(status);
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        this.isChecked = isChecked;
        if (isChecked && isClick && datasCompleted()) {
            CanBeClicked(1);
        } else {
            CanBeClicked(2);
        }
    }

    /**
     * @return 判断是否全部填写完成
     */
    public boolean datasCompleted() {
        String dataStatus = dataHiv.getRightText();
        String basicStatus = basicHiv.getRightText();
        String bisStatus = bisInfoHiv.getRightText();
        String settleStatus = settlemenHiv.getRightText();
        String rateStatus = rateHiv.getRightText();
        String limitStatus = limitHiv.getRightText();

        boolean flag = false;
        boolean isCon = true;
        String[] status = new String[]{dataStatus, basicStatus, bisStatus, settleStatus, rateStatus, limitStatus};
        for (int i = 0; i < status.length; i++) {
            if (isCon) {
                if (!"已完成".equals(status[i])) {
                    flag = false;
                    isCon = false;
                } else {
                    flag = true;
                }
            }
        }
        return flag;
    }

    /**
     * @param flag 控制是否可点击提交
     */
    public void CanBeClicked(int flag) {
        switch (flag) {
            case 1://提交可点击
                BtnStyleUtil.settingBtnStyle(mContext,submitBtn);
//                submitBtn.setEnabled(true);
//                submitBtn.setBackgroundResource(R.drawable.icon_submit);
                break;
            case 2://提交不可点击
                BtnStyleUtil.inintBtnDefaultStyle(mContext,submitBtn);
//                submitBtn.setEnabled(false);
//                submitBtn.setBackgroundResource(R.drawable.icon_nopreview);
                break;
        }

    }


    class DataEditListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {

            String phone = phoneLet.getEditContent();
            String sno = snoLet.getEditContent();
//            String remarks = remarksLet.getEditContent();

            if (!TextUtils.isEmpty(phone) && !TextUtils.isEmpty(sno)) {
                if (isChecked && datasCompleted()) {
                    CanBeClicked(1);
                } else {
                    CanBeClicked(2);
                }
                isClick = true;
            } else {
                CanBeClicked(2);
                isClick = false;
            }
        }
    }


    @Override
    public void onLeftClick(View view) {
        SPUtils.removeList(SPUtils.getList(Constant.KEY.RATE).size(), Constant.KEY.RATE);
        SPUtils.removeList(SPUtils.getList(Constant.KEY.LIMIT).size(), Constant.KEY.LIMIT);
        SPUtils.removeList(SPUtils.getList(Constant.KEY.PAPER_FILE).size(), Constant.KEY.PAPER_FILE);
        StatuUtils.removeStatu();
        SPUtils.removeHistory("IntoPiecesInfo");
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
            onLeftClick(null);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        Log.d("requireItem", " bisType " + intoPieces.getBisTypeNo());
        if (fileList != null && fileList.size() != 0)
            dataHiv.setRightText(StatuUtils.getInstance().getPaper());
        basicHiv.setRightText(StatuUtils.getInstance().getBasicData());
        bisInfoHiv.setRightText(StatuUtils.getInstance().getBisInfo());
        settlemenHiv.setRightText(StatuUtils.getInstance().getSettlement());
        rateHiv.setRightText(StatuUtils.getInstance().getRate());
        limitHiv.setRightText(StatuUtils.getInstance().getLimit());
        if (!TextUtils.isEmpty(intoPieces.getSno())) {
            snoLet.setEditContent(intoPieces.getSno());
        }
    }

    /**
     * //     * @param stub
     * //     * @return 提交所有数据
     * //
     */
    public MerAddModular.MyResponse commitData(MerAddServiceGrpc.MerAddServiceBlockingStub stub) {

        intoPieces = SPUtils.getIntoPieces();
        if (intoPieces == null) {
            Log.d("requireItem", "intoPieces为空");
        }
        MerAddModular.MerchantInfo merchantInfo = new MerAddModular.MerchantInfo();
        MerAddModular.MerInfoRequest merInfoReq = new MerAddModular.MerInfoRequest();

//                                merInfoReq.userId = userInfo.getUserNo();
//                                merInfoReq.agentNo = userInfo.getAgentNo();
        merInfoReq.sns = intoPieces.getSno();//机具SN号
//        Log.d("requireItem", );
        merInfoReq.userId = userInfo.getUserNo();
//                                merInfoReq.sns = "ZFJ1409021061";
        merInfoReq.sns = snoLet.getEditContent();
        merInfoReq.agentNo = userInfo.getAgentNo();
        merInfoReq.oneAgentNo = userInfo.getOneAgentNo();
        merInfoReq.teamId = ConfigPorperties.getInstance().getTeamId();
        //完善资料 - 商户信息
        merchantInfo.agentNo = userInfo.getAgentNo();
        merchantInfo.creator = userInfo.getAgentNo();
        merchantInfo.parentNode = userInfo.getAgentNode();
        merchantInfo.mobilephone = phone;//手机号
        merchantInfo.remark = remark;//备注
//                                merchantInfo.mobilephone = "18300070842";//手机号
//                                merchantInfo.remark = "加急";//备注
        Log.d("requireItem", " 手机号： " + merchantInfo.mobilephone + " 备注: " + merchantInfo.remark + "userId >>> " + merInfoReq.userId + " agentNo >>> " + merInfoReq.agentNo
                + " sns >>> " + merInfoReq.sns);
        //证件资料
        fileList = SPUtils.getList(Constant.KEY.PAPER_FILE);
        if (fileList != null && fileList.size() > 0) {
            MerAddModular.MerFile fileArray[] = new MerAddModular.MerFile[fileList.size()];
            MerAddModular.MerFile merFile;
            PaperFile paperFile;
            for (int i = 0; i < fileList.size(); i++) {
                merFile = new MerAddModular.MerFile();
                paperFile = fileList.get(i);
                merFile.fileName = paperFile.getFileName();
                merFile.file = FileUtil.getByte(paperFile.getFilePath());
                fileArray[i] = merFile;
            }
            merInfoReq.merFile = fileArray;
        }
        //基本信息
        merchantInfo.lawyer = intoPieces.getLegalPerson();//法人姓名
        merchantInfo.idCardNo = intoPieces.getIdCardNo();//法人身份证
        Log.d("PersonId", " 身份证： " + merchantInfo.idCardNo);
        //经营信息
        merchantInfo.merchantName = intoPieces.getMerchantName();//商户名称
        merchantInfo.businessType = intoPieces.getBisTypeNo();//商户类别传MCC码
        merchantInfo.industryType = intoPieces.getMcc();
        merchantInfo.address = intoPieces.getArea() + "-" + intoPieces.getAddress();//详细地址
//        Log.d("requireItem", " 法人姓名 " + merchantInfo.lawyer + " | 法人身份证 " + merchantInfo.idCardNo
//                + " | 商户名称" + merchantInfo.merchantName + " | MCC:" + merchantInfo.businessType
//        );
//                                merchantInfo.city = intoPieces.getArea();//所在地
//                                merchantInfo.city = "深圳市";//所在地
//                                merchantInfo.address = "南山区科技园同方信息港";//详细地址
//                                merchantInfo.merchantName = "移联天下";//商户名称
//                                merchantInfo.businessType = "42543";//商户类别

//                                merchantInfo.agentNo = userInfo.getAgentNo();
        merchantInfo.merchantType = intoPieces.getMerchantType();
        //结算信息
        MerAddModular.MerCardInfo merCardInfo = new MerAddModular.MerCardInfo();
//                              merCardInfo.accountType = intoPieces.getAccountType();//账户类型
//                              merCardInfo.accountName = intoPieces.getAccountName();//开户名
//                              merCardInfo.accountNo = intoPieces.getAccountNo();//开户账号
//                              merCardInfo.bankName = intoPieces.getBankName();//开户行名称
//                              merCardInfo.cnapsNo = intoPieces.getCnapsNo();//联行行号
//                              merCardInfo.accountName = "移付宝";//开户名
//                              merCardInfo.accountType = "1";//账户类型
//                              merCardInfo.accountNo = "622714546121369889";//开户账号
//                              merCardInfo.bankName = "民生银行";//开户行名称
//                              merCardInfo.cnapsNo = "1203460122";//联行行号
//                              merCardInfo.id="001";
        MerAddModular.MerRequireItem item1 = new MerAddModular.MerRequireItem();
        item1.mriId = "1";//账户类型
        item1.content = intoPieces.getAccountType();
//                                item1.content = "对公";
        MerAddModular.MerRequireItem item2 = new MerAddModular.MerRequireItem();
        item2.mriId = "2";//开户名
        item2.content = intoPieces.getAccountName();
//                                item2.content = "gaowei";
        MerAddModular.MerRequireItem item3 = new MerAddModular.MerRequireItem();
        item3.mriId = "3";//开户账号
        item3.content = intoPieces.getAccountNo();
//                                item3.content = "1234569846165165";
        MerAddModular.MerRequireItem item4 = new MerAddModular.MerRequireItem();
        item4.mriId = "4";//开户银行支行
        item4.content = intoPieces.getZh();
//                                item4.content = "中国银行南山支行";
        MerAddModular.MerRequireItem item5 = new MerAddModular.MerRequireItem();
        item5.mriId = "5";//联行行号
        item5.content = intoPieces.getCnapsNo();
//                                item5.content = "106448656222";
        MerAddModular.MerRequireItem item6 = new MerAddModular.MerRequireItem();
        item6.mriId = "6";//身份证号
        item6.content = intoPieces.getIdCardNo();

        MerAddModular.MerRequireItem item7 = new MerAddModular.MerRequireItem();
        item7.mriId = "7";//地址
        item7.content = intoPieces.getArea() + "-" + intoPieces.getAddress();
        Log.d("requireItem", " 地址: " + item7.content);
//                                item6.content = "广东省-深圳市-同方信息港A栋10楼";
        MerAddModular.MerRequireItem item15 = new MerAddModular.MerRequireItem();
        item15.mriId = "15";//开户地区
        item15.content = intoPieces.getZhAddress();
        Log.d("requireItem", " 开户地区: " + item15.content);
        MerAddModular.MerRequireItem requireItemArray[] = new MerAddModular.MerRequireItem[8];
        requireItemArray[0] = item1;
        requireItemArray[1] = item2;
        requireItemArray[2] = item3;
        requireItemArray[3] = item4;
        requireItemArray[4] = item5;
        requireItemArray[5] = item6;
        requireItemArray[6] = item7;
        requireItemArray[7] = item15;
        for (int i = 0; i < requireItemArray.length; i++) {
            Log.d("requireItem", " 进件项： " + requireItemArray[i].id + " -->" + requireItemArray[i].content);
        }

        //服务费率
        rateList = SPUtils.getList(Constant.KEY.RATE);
        MerAddModular.MerServiceRate[] merRates = new MerAddModular.MerServiceRate[rateList.size()];
        MerAddModular.MerServiceRate merSerRate;
        RateInfo rateInfo;
        if (rateList != null && rateList.size() > 0) {
            for (int i = 0; i < rateList.size(); i++) {
                merSerRate = new MerAddModular.MerServiceRate();
                rateInfo = rateList.get(i);
                if ("1".equals(rateInfo.getFixedRate()))
                    continue;
//                merSerRate.serviceId = rateInfo.getServiceId();
//                merSerRate.cardType = rateInfo.getCardType();
//                merSerRate.holidaysMark = rateInfo.getServiceTime();
//                merSerRate.rateType = rateInfo.getRateType();
                merSerRate.id = rateInfo.getId();
                Log.d("merSerRate.id", " merSerRate.id:" + merSerRate.id);
                switch (Integer.parseInt(rateInfo.getRateType())) {
                    case 1:
                        merSerRate.singleNumAmount = rateInfo.getSingle_num_amount();
//                        Log.d("rate", " type = 1 --> " + merSerRate.singleNumAmount);
                        break;
                    case 2:
                        merSerRate.rate = rateInfo.getRate();
//                        Log.d("rate", " type = 2 --> " + merSerRate.rate);
                        break;
                    case 3:
                        merSerRate.safeLine = rateInfo.getSafe_line();
                        merSerRate.rate = rateInfo.getRate();
                        merSerRate.capping = rateInfo.getCapping();
//                        Log.d("rate", " type = 3 --> " + merSerRate.safeLine + " | "
//                                + merSerRate.rate + " | " + merSerRate.singleNumAmount);
                        break;
                    case 4:
                        merSerRate.rate = rateInfo.getRate();
                        merSerRate.singleNumAmount = rateInfo.getSingle_num_amount();
                        break;
                    case 5:
                        merSerRate.ladder1Rate = rateInfo.getLdr1Rate();
                        merSerRate.ladder1Max = rateInfo.getLdr1Max();
                        merSerRate.ladder2Rate = rateInfo.getLdr2Rate();
                        break;
                }
                merRates[i] = merSerRate;
            }

        }
//                                服务限额
        limitList = SPUtils.getList(Constant.KEY.LIMIT);
        LimitInfo limit;
        MerAddModular.MerServiceQuota[] merQuotas = new MerAddModular.MerServiceQuota[limitList.size()];
        MerAddModular.MerServiceQuota merQuota;
        if (limitList != null && limitList.size() > 0) {
            for (int i = 0; i < limitList.size(); i++) {
                merQuota = new MerAddModular.MerServiceQuota();
                limit = limitList.get(i);
                if ("1".equals(limit.getFixedQuota()))
                    continue;
//                merQuota.serviceId = limit.getServiceId();
//                merQuota.merchantNo = String.valueOf(i);
//                merQuota.cardType = limit.getCardType();
//                merQuota.holidaysMark = limit.getServiceTime();
                merQuota.singleMinAmount = limit.getMinAmount();
                merQuota.singleCountAmount = limit.getCountAmount();
                merQuota.singleDayAmount = limit.getDayAmount();
                merQuota.singleDaycardAmount = limit.getDayCardAmount();
                merQuota.singleDaycardCount = limit.getDayCardConut();
                merQuota.id = limit.getId();
//                merQuota.fixedMark = limit.getFixedQuota();
//                Log.d("merQuota.id", " merQuota.id:" +  merQuota.id);
                merQuotas[i] = merQuota;
            }
        }

        //业务产品
        MerAddModular.MerBusinessProduct product = new MerAddModular.MerBusinessProduct();
//                                product.bpId = "001";
        product.bpId = intoPieces.getProId();
//        product.merchantNo = "456";
//        product.status = "0";
        product.saleName = userInfo.getAgentName();

//                                merInfoReq.merchantNo = "YFB";

        merInfoReq.merInfo = merchantInfo;
        merInfoReq.merCardInfo = merCardInfo;
        if (merRates.length != 0) {
            merInfoReq.merServiceRate = merRates;
        }
        if (merQuotas.length != 0) {
            Log.d("continue", " merQuotas.length != 0");
            merInfoReq.merServiceQuota = merQuotas;
        }
        merInfoReq.merBusPro = product;
        merInfoReq.merRequireItem = requireItemArray;
        serviceInfos = DataUtils.getInstance().getSerInfoArray();
        MerAddModular.ServiceInfo serviceInfo;
        for (int i = 0; i < serviceInfos.length; i++) {
            serviceInfo = serviceInfos[i];
            Log.d("serviceInfos", " serviceId " + serviceInfo.serviceId + " >>>> bankCard " + serviceInfo.bankCard +
                    " >>>> business " + serviceInfo.business + " >>>> serviceStatus " + serviceInfo.serviceStatus
            );
        }

        merInfoReq.serviceInfo = serviceInfos;
        Log.d("saki", "merFile >>> " + merInfoReq.merFile.length +
                "merServiceRate >>> " + merInfoReq.merServiceRate.length +
                "merServiceRate >>> " + merInfoReq.merServiceRate.length
        );
        return stub.addMerchant(merInfoReq);
    }


}
